﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;
using System.Reflection;
using GameServer.Servers;

namespace GameServer.Controller
{
    /// <summary>
    /// Controller管理类
    /// </summary>
    class ControllerManager
    {
        private Dictionary<RequestCode, BaseController> controllerDic = new Dictionary<RequestCode, BaseController>();
        private Server server;

        public ControllerManager(Server _server)
        {
            this.server = _server;
            InitController();
        }

        private void InitController()
        {
            DefaultController defaultController = new DefaultController();
            controllerDic.Add(defaultController.RequestCode, defaultController);
            controllerDic.Add(RequestCode.User, new UserController());
            controllerDic.Add(RequestCode.Room, new RoomController());
        }

        /// <summary>
        /// 分发给相应的Controller来处理客户端的数据
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="actionCode"></param>
        /// <param name="data"></param>
        /// <param name="client"></param>
        public void HandleRequest(RequestCode requestCode, ActionCode actionCode, string data, Client client)
        {
            BaseController controller;
            bool isGet = controllerDic.TryGetValue(requestCode, out controller);
            if (!isGet)
            {
                Console.WriteLine("无法得到" + requestCode + "所对应的Controller，无法处理请求");
            }
            string methodeName = Enum.GetName(typeof(ActionCode), actionCode);
            MethodInfo mi = controller.GetType().GetMethod(methodeName);
            if (mi == null)
            {
                Console.WriteLine("[警告]在Controller" + controller.GetType() + "中没有对应的处理方法:[" + methodeName +"]");
            }
            object[] parameters = new object[] { data, client, server };
            object o = mi.Invoke(controller, parameters);
            if (o == null || string.IsNullOrEmpty(o as string))
                return;
            //请求处理完之后，给客户端响应
            server.SendResponse(client, actionCode, o as string);
        }
    }
}
